# coding: utf-8

from flask import Blueprint, render_template, redirect, url_for, flash, request
from flask_login import login_user, logout_user, login_required, current_user
from flask_principal import Permission, RoleNeed
from flask_login import LoginManager
from borrow_card.forms import BorrorCardAddForm
from db.models import db, User, BorrowCard, SysUserRole
from permission_control import permission_required
from const import BorrowCardApplyStatus, PERMISSION
from datetime import datetime
from dateutil.relativedelta import relativedelta
from sqlalchemy import func
from config import app
from log import logger
from random import randint

borrow_card_approval_blueprint = Blueprint('card_manage', __name__)


@borrow_card_approval_blueprint.route('/admin/card/apply/list', methods=['GET', 'POST'])
@login_required
@permission_required(PERMISSION.PERM_BORROW_CARD_APPROVAL.KEY)
def card_apply_list():
    apply_user_list = User.query.filter_by(
        borrow_card_apply_status=BorrowCardApplyStatus.APPLYING.value).all()
    query = db.session.query(
            SysUserRole, User, BorrowCard
        ).outerjoin(
            User, SysUserRole.user_id==User.id
        ).outerjoin(
            BorrowCard, User.id == BorrowCard.user_id
        ).where(
            SysUserRole.role_key == 'ROLE_USER'
        ).order_by(
            User.id.desc()
        )
    logger.info(query)
    borrow_card_list = query.all()
    return render_template('card_manage/card_list.html', 
                           borrow_card_list=borrow_card_list,
                           apply_user_list=apply_user_list)


@borrow_card_approval_blueprint.route('/admin/card/approval/<int:user_id>', methods=['GET', 'POST'])
@login_required
@permission_required(PERMISSION.PERM_BORROW_CARD_APPROVAL.KEY)
def card_approval(user_id):
    user = User.query.filter_by(id=user_id).first()
    form = BorrorCardAddForm(user_id=user.id)
    if request.method == "POST":
        if form.validate_on_submit():
            new_borrow_card = BorrowCard.query.filter_by(user_id=user.id).first()
            if new_borrow_card is None:
                new_borrow_card = BorrowCard()
                new_borrow_card.user_id = user.id
            new_borrow_card.card_id = form.card_id.data
            new_borrow_card.valid_until = form.valid_until.data
            new_borrow_card.borrow_limit = form.borrow_limit.data
            print(f"new_borrow_card: {new_borrow_card}")
            db.session.add(new_borrow_card)
            user.borrow_card_apply_status = BorrowCardApplyStatus.APPLIED.value
            db.session.commit()
            form.populate_obj(new_borrow_card)
            flash('借阅卡审批通过！', 'success')
        else:
            flash(f'借阅卡审批失败！{form.errors}', 'danger')
        return redirect(url_for('card_manage.card_apply_list'))
    else:
        now = datetime.now() + relativedelta(months=1)
        new_card_id = f"CARD{int(user.user_idcard[-6:]):08d}" \
                      + f"{randint(0,100):02d}"
        form.card_id.data = new_card_id
        # form.valid_until.data = now.strftime('%Y/%m/%d')
        form.borrow_limit.data = 3
    return render_template('card_manage/card_approval.html', form=form, user=user)
